<template>
  <view>
    <view
      v-for="(hospital, hIdx) in hospitals"
      :key="hospital.name"
      class="hospital-section">
      <view class="hospital-header">
        <text class="hospital-name">{{ hospital.name }}</text>
        <button @click="clearHospital(hIdx)" size="mini" type="warn">
          清空
        </button>
        <up-checkbox
          v-model="hospital.allSelected"
          @change="toggleAllServicesSelection(hospital)"
          shape="circle"
          >全选</up-checkbox
        >
      </view>
      <view
        v-for="(service, sIdx) in hospital.services"
        :key="service.id"
        class="service-item">
        <up-checkbox
          v-model="service.selected"
          @change="toggleServiceSelection(hospital, service)"
          shape="circle"></up-checkbox>
        <view class="service-info">
          <view class="service-name">{{ service.name }}</view>
          <view class="service-desc">{{ service.description }}</view>
          <view class="service-price">￥{{ service.price.toFixed(2) }}</view>
        </view>
      </view>
    </view>
    <view class="total-section">
      总金额：<text class="price">￥{{ totalAmount.toFixed(2) }}</text>
    </view>
  </view>
</template>

<script setup>
const hospitals = ref([
  {
    name: "寿光洛城街道卫生院",
    services: [
      {
        id: 1,
        name: "伤口拆线（1-5针）",
        description: "创面清理 | 更换敷料",
        price: 155.0,
        selected: true,
      },
    ],
    allSelected: false,
  },
  {
    name: "寿光市妇幼医院",
    services: [
      {
        id: 2,
        name: "伤口拆线（6-10针）",
        description: "创面清理 | 更换敷料",
        price: 189.0,
        selected: false,
      },
      {
        id: 3,
        name: "小伤口换药（伤口＜5cm）",
        description: "创面清理 | 更换敷料",
        price: 168.0,
        selected: false,
      },
    ],
    allSelected: false,
  },
]); // 切换单个服务选中状态
function toggleServiceSelection(hospital, service) {
  service.selected = !service.selected;
  hospital.allSelected = hospital.services.every((s) => s.selected);
}

// 切换医院下所有服务选中状态
function toggleAllServicesSelection(hospital) {
  hospital.services.forEach((s) => (s.selected = hospital.allSelected));
}

// 清空某医院下所有服务
function clearHospital(hIdx) {
  hospitals.value[hIdx].services.forEach((s) => (s.selected = false));
  hospitals.value[hIdx].allSelected = false;
}

// 计算总金额
const totalAmount = computed(() => {
  return hospitals.value.reduce((sum, hospital) => {
    return (
      sum +
      hospital.services
        .filter((s) => s.selected)
        .reduce((s, item) => s + item.price, 0)
    );
  }, 0);
});
</script>

<style lang="scss" scoped>
.price-section {
  display: flex;
  align-items: center;
  .price {
    color: red;
    margin-right: 10px;
  }
}

.all-select-section {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.total-section {
  margin: 20px 0;
  font-size: 18px;
  font-weight: bold;
}
</style>
